﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using static System.Threading.Thread;
using static System.Console;
using KongMing.Common;

namespace TaskUnitProject
{
    /// <summary>
    /// 3.Task取消任务的执行
    /// CancellationTokenSource source=new CancellationTokenSource();
    /// source.CancelAfter(5000)  实现5秒后自动取消任务
    /// source.Token.Register(()=>{})) 注册取消任务时触发的回调函数
    /// </summary>
    public class TaskUnit_1_3:UnitBase
    {
        public static void Go()
        {
            CancellationTokenSource source=new CancellationTokenSource();

            //创建任务被取消后执行的操作
            source.Token.Register(() => { WriteLine("任务被取消后执行操作"); });
            
            int index = 0;
            //开启一个task任务
            Task task1 = Task.Run(() =>
            {
                while (!source.IsCancellationRequested)
                {
                    SleepSeconds(1);
                    WriteLine($"第{++index}次执行，线程运行中...");
                }
            });
            //五秒后取消任务执行
            source.CancelAfter(5000);
        }
    }
}
